package com.xxx.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xxx.common.UserAuth;
import com.xxx.common.dto.JsonResult;
import com.xxx.interceptor.AuthorityType;
import com.xxx.interceptor.UserAuthority;
import com.xxx.model.SysUserBasis;
import com.xxx.service.SysUserBasisService;

@Controller
@UserAuthority(authorityType = AuthorityType.NoValidate)
public class AccountController {
	
	@Autowired
	private SysUserBasisService sysUserBasisService;
	
	/**
	 * 登录页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value={"account/login.html"},method = RequestMethod.GET)
	public String index() throws Exception{
		return "account/login";
	}
	
	/**
	 * 用户登录
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "account/login", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public JsonResult save(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String account = request.getParameter("account");
		String pwd = request.getParameter("pwd");
		SysUserBasis user = sysUserBasisService.login(account, pwd);
		if(user != null){
			//设置登录票据
			UserAuth.setUserAuth(user.getId(), user.getUsername(), response);
			return JsonResult.ok();
		}
		return JsonResult.build(-1, "用户名或者密码错误!");
	}
	
	/**
	 * 退出登录
	 * @param response
	 * @return
	 */
	@RequestMapping(value="account/logout", method=RequestMethod.GET)
	public String logout(HttpServletResponse response){
		UserAuth.cleanUserAuth(response);
		return "redirect:/account/login.html";
	}
}
